// pages/home-page/index/index.js
const util = require("../../../utils/util.js");
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    animate:{},
    getEnergyShow:false,
    signEnergyCount: '',
    hasExamPower:false,
    CDNPATH:app.globalData.CDNPATH,
    imgUrls: [],
    noticeList: [],
    statusBarHeight:app.globalData.statusBarHeight,
    navBarHeight: app.globalData.navBarHeight,
    guideShow: true,
    imgDefaultUrls: [],
    currentSwiper: 0,
    countList: [],
    stage: "all",
    customerList: [],
    customerPage: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
    },
    visitorList: [],
    visitorPage: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
    },
    hasBack: false,
    showSkeleton: true,
    firstShow: false,
    guideShowLive: false,
    guideShowTrain: false,
    loading: false,
    vrLoading: false,
    userInfo: {},
    trainList: [],
    levelList: [],
    subscribeInfo: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideHomeButton();
    this.setData({
      firstShow: !app.globalData.userInfo.firstLogin,
      navBarHeight: app.globalData.navBarHeight,
      userInfo: app.globalData.userInfo,
    });
    const permissionCodes = app.globalData.permissionCodes || []
    const hasPower = permissionCodes.includes('myExam')
    this.setData({
      hasExamPower:hasPower
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(this.data.CDNPATH)
    app.api
      .post({
        url: "advertise_list",
      })
      .then((res) => {
        let arr = [];
        if ( res && res.length > 0) {
          res.map((v, k) => {
            arr.push(v);
          });
          this.setData({
            imgUrls: arr,
          });
        } else {
          this.setData({
            imgDefaultUrls: [
              { coverMaterialUrl: '/assets/images/index_bg.png' },
            ],
          });
        }
      });
    const { stage } = this.data;
    this.getList(stage);
    this.getTrainList();
    // this.getMessageSubscribeInfo();
    this.getMessageList();
    this.getUserEnergy()
    this.loginGetEnergy()
    this.getLevelList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      loading: false,
      vrLoading: false,
    });
  },
  getUserEnergy () {
    app.api.get({
      url: "get_user_energy",
    }).then(res=>{

    })
  },
  loginGetEnergy () {
    app.api.get({
      url: "getLoginEnergy",
    }).then(res=>{
      if(res.data > 0){
        this.setData({
          getEnergyShow:true,
          signEnergyCount: res.data
        })
      }
    })
  },
  closeEnergyShow () {
    this.setData({
      getEnergyShow:false
    })
  },
  async getMessageList() {
    console.log("this.data.isGetMessageList");
    try {
      let res = await app.api.post({
        url: "broadcast_indexMessageList",
        data: { currentPage: 1, pageSize: 5 },
      });
      this.setData({
        noticeList: res && res.list ? res.list : [],
      });
    } catch (e) {}
  },
  swiperChange: function (e) {
    this.setData({
      currentSwiper: e.detail.current,
    });
  },
  addCustomer: function () {
    wx.navigateTo({
      url: `/pages/home-page/add-customer/addCustomer?hitTypeId=8`,
    });
  },
  async getMessageSubscribeInfo() {
    let res = await app.api.post({
      url: "wxmess_subscribeInfo",
    });
    console.log(res);
    this.setData({
      subscribeInfo: res,
    });
  },
  notifySubscribe(res) {
    let itemSettings = res;
    let templateIds = [];

    for (let item in itemSettings) {
      if (itemSettings[item] === "accept") {
        templateIds.push(item);
      }
    }
    app.api
      .post({
        url: "wxmess_subscribe",
        data: { templateIds: templateIds },
      })
      .then((res) => {
        console.log("订阅成功回传");
      });

    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        console.log("getSetting", res);
        console.log(res.authSetting);
        // res.authSetting = {
        //   "scope.userInfo": true,
        //   "scope.userLocation": true
        // }
        console.log(res.subscriptionsSetting);
        let itemSettings = res.subscriptionsSetting.itemSettings;
        let templateIds = [];
        if (itemSettings) {
          for (let item in itemSettings) {
            if (itemSettings[item] === "accept") {
              templateIds.push(item);
            }
          }
          app.api
            .post({
              url: "wxmess_subscribe",
              data: { templateIds: templateIds },
            })
            .then((res) => {
              console.log("订阅成功回传");
            });
        }
      },
    });
  },

  messageCenter(e) {
    //以后会有用
    // wx.getSetting({
    //   withSubscriptions: true,
    //   success(res) {
    //     console.log("getSetting", res);
    //     console.log(res.authSetting);
    //     // res.authSetting = {
    //     //   "scope.userInfo": true,
    //     //   "scope.userLocation": true
    //     // }
    //     console.log(res.subscriptionsSetting);
    //     // res.subscriptionsSetting = {
    //     //   mainSwitch: true, // 订阅消息总开关
    //     //   itemSettings: {   // 每一项开关
    //     //     SYS_MSG_TYPE_INTERACTIVE: 'accept', // 小游戏系统订阅消息
    //     //     SYS_MSG_TYPE_RANK: 'accept'
    //     //     zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: 'reject', // 普通一次性订阅消息
    //     //     ke_OZC_66gZxALLcsuI7ilCJSP2OJ2vWo2ooUPpkWrw: 'ban',
    //     //   }
    //     // }
    //   },
    // });
    let target = e.target.dataset.target;
    let id = e.target.dataset.id;
    console.log(this.data.subscribeInfo);
    if (this.data.subscribeInfo && this.data.subscribeInfo.isShow === true) {
      let tmplIds = this.data.subscribeInfo.templateId
        ? this.data.subscribeInfo.templateId
        : [];
      console.log("requestSubscribeMessage");
      wx.requestSubscribeMessage({
        //tmplIds: ["s0d5fQCZyqNByYcOOgXnnJ21JiEwv0A5cdtsQKIU0CE"],
        tmplIds: tmplIds,
        success: (res) => {
          console.log(res);
          console.log("授权成功");
          this.messageCenterJumpOpt(target,id);
          if (res.errMsg === "requestSubscribeMessage:ok") {
            this.notifySubscribe(res);
          }
        },
        fail: (res) => {
          console.log(res);
          console.log("授权失败");
          this.messageCenterJumpOpt(target,id);
        },
      });
    } else {
      this.messageCenterJumpOpt(target,id);
    }
  },
  messageCenterJumpOpt(target,id) {
    this.getMessageSubscribeInfo(); //更新订阅状态
    if (target === "detail") {
      this.msgDetail(id);
    } else if (target === "list") {
      this.moreMsg();
    }
  },
  msgDetail(event) {
    const id =  event.currentTarget.dataset.id
    wx.navigateTo({
      url: `/myself/pages/message-detail/message-detail?id=${id}`,
    })
  },
  moreMsg() {
    wx.navigateTo({
      url: `/myself/pages/message-center/message-center?hitTypeId=2`,
    })
  },
  check: function (e) {
    // let code = ["banner"];
    // let arr = util.getArrEqual(code, app.globalData.roles);
    // if (arr.length === 0) {
    //   wx.showToast({
    //     title: "暂无权限",
    //     icon: "none",
    //     duration: 1000,
    //   });
    //   return;
    // }
    const { item } = e.currentTarget.dataset;
    app.api.post({
      url: "advertise_access_record",
      data: {
        aid: item.id,
      },
    });
    switch (item.type) {
      case 'PICTURE':
        wx.previewImage({
          urls: [item.contentMaterialUrl],
        });
        break;
      case 'VIDEO':
        this.setData({
          videoShow: true,
          videoSrc: item.contentMaterialUrl,
        });
        setTimeout(function () {
          //将点击视频进行播放
          var videoContext = wx.createVideoContext("video");
          videoContext.requestFullScreen();
          videoContext.play();
        }, 500);
        break;
      case "LINK":
        wx.navigateTo({
          url: `/pages/webview/webview?type=ad&hitTypeId=1&url=${encodeURIComponent(
            item.link
          )}`,
        });
        break;
      case "PRODUCT":
        wx.navigateTo({
          url: `/product/pages/detail/detail?url=${
            item.overviewPictureUrl || ""
          }&hitTypeId=1&productId=${item.productId}&productCode=${
            item.productCode
          }`,
        });
        break;
      case "LOADING_PAGE":
        wx.navigateTo({
          url: "/pages/landing-page/landingPage?hitTypeId=1",
        });
        break;
      default:
        break;
    }
  },
  screenChange(e) {
    let fullScreen = e.detail.fullScreen; //值true为进入全屏，false为退出全屏
    if (!fullScreen) {
      //退出全屏
      var videoContext = wx.createVideoContext("video");
      videoContext.stop();
      this.setData({
        videoShow: false,
      });
    } else {
      //进入全屏
    }
  },
  checkTask: function (e) {
    const {
      id,
      latestStatus: status,
      productId,
      productCode,
      shareId,
    } = e.currentTarget.dataset.item;
    let params = { customerId: id, productId, productCode };
    let url;
    switch (status) {
      case "analysis":
        url = `/pages/home-page/customer-tag/customerTag?customerId=${id}&origin=1&hitTypeId=21`;
        break;
      case "proposal":
        url = `/pages/home-page/project/project?customerId=${id}&productId=${productId}&productCode=${productCode}&sensors_ext=06-02&hitTypeId=19`;
        break;
      case "check":
        url = `/pages/home-page/project/project?shareId=${shareId}&customerId=${id}&productId=${productId}&productCode=${productCode}&hitTypeId=20`;
        break;
      default:
        break;
    }
    this.setData({
      loading: true,
    });
    url &&
      wx.navigateTo({
        url,
      });
  },
  train(e) {
    const { id: customerId, productId } = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/home-page/train/train?customerId=${customerId}&productId=${productId}&hitTypeId=17`,
    });
  },
  toSerial() {
    let code = ["serial"];
    let arr = util.getArrEqual(code, app.globalData.roles);
    if (arr.length === 0) {
      wx.showToast({
        title: "暂无权限",
        icon: "none",
        duration: 1000,
      });
      return;
    }
    wx.navigateTo({
      url: `/product/pages/audioCourse/audioCourse?hitTypeId=7`,
    });
  },
  toDemonstration(e) {
    let code = ["e-live"];
    let arr = util.getArrEqual(code, app.globalData.roles);
    if (arr.length === 0) {
      wx.showToast({
        title: "暂无权限",
        icon: "none",
        duration: 1000,
      });
      return;
    }
    console.log(e);
    if (e.currentTarget.dataset.id === "-1") {
      wx.navigateTo({
        url: `/pages/live-demonstration/liveDemonstration?sensors_ext=03-01&hitTypeId=4`,
      });
    } else {
      const { id: customerId, productId, name } = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: `/pages/live-demonstration/liveDemonstration?customerId=${customerId}&productId=${productId}&userName=${name}&sensors_ext=03-00&hitTypeId=18`,
      });
    }
  },
  showCustomer (e) {
    const { stage } = e.currentTarget.dataset
    this.setData({
      stage,
    });
    this.getList(stage);
  },
  getList(stage) {
    if (stage === "visitor") {
      this.setData({
        "visitorPage.currentPage": 1,
      });
      this.getVisitorList();
    } else {
      this.setData({
        "customerPage.currentPage": 1,
        showSkeleton: false,
      });
      // this.getCustomerList();
    }
  },
  getCustomerList: function (params) {
    let { customerPage, stage, customerList } = this.data;
    app.api
      .post({
        url: "customer_manage_homeList",
        data: {
          currentPage: customerPage.currentPage,
          pageSize: customerPage.pageSize,
          stage,
        },
      })
      .then((res) => {
        customerPage.currentPage === 1
          ? (customerList = res.list)
          : customerList.push(...res.list);
        this.setData({
          customerList,
          "customerPage.total": Number(res.total),
          showSkeleton: false,
        });
      });
  },
  loadList: function () {
    let { customerPage, stage, visitorPage, customerList, visitorList } =
      this.data;
    if (stage === "visitor") {
      if (visitorPage.total > visitorList.length) {
        this.setData({
          "visitorPage.currentPage": visitorPage.currentPage + 1,
        });
        this.getVisitorList();
      }
    } else {
      if (customerPage.total > customerList.length) {
        this.setData({
          "customerPage.currentPage": customerPage.currentPage + 1,
        });
        // this.getCustomerList();
      }
    }
  },
  getVisitorList: function (params) {
    let { visitorPage, visitorList } = this.data;
    app.api
      .post({
        url: "customer_manage_customerVisitorPage",
        data: visitorPage,
      })
      .then((res) => {
        visitorPage.currentPage === 1
          ? (visitorList = res.list)
          : visitorList.push(...res.list);
        this.setData({
          visitorList,
          "visitorPage.total": Number(res.total),
        });
      });
  },
  goToCustomer: function (e) {
    const { id } = e.currentTarget.dataset;
    if (id) {
      wx.navigateTo({
        url: `/pages/home-page/customer-detail/customerDetail?id=${id}&hitTypeId=15`,
      });
    }
  },
  start() {
    app.api
      .get({
        url: "cpic_user_markFirstLogin",
      })
      .then((res) => {
        app.globalData.userInfo.firstLogin = 1;
        wx.setStorageSync("userInfo", JSON.stringify(app.globalData.userInfo));
        this.setData({
          firstShow: false,
          guideShowLive: true,
        });
      });
  },
  openVR(e) {
    const {
      id: customerId,
      productId,
      name,
      age,
      birthday,
      sex,
    } = e.currentTarget.dataset.item;
    const { vrLoading } = this.data;
    if (!vrLoading) {
      this.setData({
        vrLoading: true,
      });
      app.api
        .post({
          url: "config_value",
          data: {
            key: "vr.flag",
          },
        })
        .then((res) => {
          if (Boolean(Number(res.value))) {
            // 允许打开
            app.api
              .post({
                url: "customer_stage_getShareURL",
                data: {
                  customerId,
                  productId,
                },
              })
              .then((res) => {
                const userCode = `"${res.userCode}"`;
                const viewUrl = encodeURIComponent(
                  `${res.shareUrl}shareid=${res.shareId}&paramId=${
                    res.paramId
                  }&source=${res.source}&productSource=${
                    res.productSource
                  }&productCode=${res.productCode}&userCode=${util.encode(
                    userCode
                  )}`
                );
                wx.reLaunch({
                  url: `/pages/tic/room_webview/room/room?sensors_ext=04-02&hitTypeId=16&viewUrl=${viewUrl}&agentId=${app.globalData.userInfo.userId}&agentName=${app.globalData.userInfo.realName}&productId=${productId}&customerId=${customerId}&customerName=${name}&customerAge=${age}&customerSex=${sex}&customerBirthday=${birthday}`,
                });
              })
              .finally(() => {
                this.setData({
                  vrLoading: false,
                });
              });
          } else {
            wx.showToast({
              title: "敬请期待",
              icon: "none",
              duration: 2000,
            });
            this.setData({
              vrLoading: false,
            });
          }
        })
        .catch(() => {
          this.setData({
            vrLoading: false,
          });
        });
    }
  },
  openVRThrottle: util.throttle(function (e) {
    this.openVR(e[0]);
  }),
  // 情景剧场
  goToScene () {
    wx.navigateTo({
      url: `/product/pages/sceneTheatre/sceneTheatre`,
    });
  },
  // 素材库（现场演示）
  goToMaterial () {
    wx.navigateTo({
      url:  `/pages/live-demonstration/liveDemonstration`,
    })
  },
  // 精品连载
  goToboutique () {
    wx.navigateTo({
      url: `/product/pages/topicList/topicList`,
    });
  },
  // 现场演示
  goToPresentation () {
    wx.navigateTo({
      url: `/pages/live-demonstration/liveDemonstration`,
    });
  },
  goToVR() {
    let code = ["vr-room"];
    let arr = util.getArrEqual(code, app.globalData.roles);
    if (arr.length === 0) {
      wx.showToast({
        title: "暂无权限",
        icon: "none",
        duration: 1000,
      });
      return;
    }
    const { userInfo } = this.data;
    wx.reLaunch({
      url: `/pages/tic/room_webview/room/room?viewUrl=&agentId=${userInfo.userId}&agentName=${userInfo.realName}&sensors_ext=04-02&hitTypeId=3`,
    });
  },
  getTrainList() {
    app.api
      .post({
        url: "coaching_vx_student_session_list_my",
        data: {
          activityStatus: "inProgress",
          currentPage: 1,
          pageSize: 999,
        },
      })
      .then((res) => {
        this.setData({
          trainList: res.list || []
        });
      });
  },
  getLevelList () {
    app.api
      .get({
        url: "qry_user_level",
        data: {},
      })
      .then((res) => {
        this.setData({
          levelList: res || []
        });
      });
  },
  toLevelScene (e) {
    const { id, levelName, status} = e.currentTarget.dataset.item
    if (status === 'lock') {
        wx.showToast({
        title: "暂未解锁",
        icon: "none",
        duration: 2000,
      });
      return false
    }
    console.log('id',id)
    wx.navigateTo({
      url: `/pages/level-scene/list/list?levelId=${id}&levelName=${levelName}`,
    });
  },
  myTrainAll() {
    // let code = ["energy"];
    // let arr = util.getArrEqual(code, app.globalData.roles);
    // if (arr.length === 0) {
    //   wx.showToast({
    //     title: "暂无权限",
    //     icon: "none",
    //     duration: 1000,
    //   });
    //   return;
    // }
    wx.navigateTo({
      url: `/myself/pages/my-training/list/list?hitTypeId=6`,
    });
  },
  toMyTraining(e) {
    // let code = ["energy"];
    // let arr = util.getArrEqual(code, app.globalData.roles);
    // if (arr.length === 0) {
    //   wx.showToast({
    //     title: "暂无权限",
    //     icon: "none",
    //     duration: 1000,
    //   });
    //   return;
    // }
    const { item } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/myself/pages/my-training/detail/detail?coachingSessionId=${item.coachingSessionId}&hitTypeId=5`,
    });
  },
  closeGuide(e) {
    let index = e.currentTarget.dataset.type;
    console.log(e);
    switch (index) {
      case "live":
        if (
          !app.globalData.userInfo.firstCoaching &&
          this.data.trainList.length > 0
        ) {
          this.setData({
            guideShowLive: false,
            guideShowTrain: true,
          });
        } else {
          this.setData({
            guideShowLive: false,
          });
        }
        break;
      case "train":
        this.setData({
          guideShowTrain: false,
        });
        break;
      default:
        break;
    }
  },
  stopTouchMove () {
    return false
  }
});
